﻿using NModbus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace DuBaiCoffee2.Model
{
    public class RobotSerialPortLeft
    {
        private static RobotSerialPortLeft instance;
        private RobotSerialPortLeft() { }

        public static RobotSerialPortLeft Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new RobotSerialPortLeft();
                }
                return instance;
            }
        }
        public IModbusMaster _modbusMaster;
        public string _ipadress;
        public int _port;

        public void Initialization(string ipadress, int port)
        {
            _ipadress = ipadress;
            _port = port;

            TcpClient tcpClient = new TcpClient(_ipadress, _port);
            var factory = new ModbusFactory();
            _modbusMaster = factory.CreateMaster(tcpClient);
        }
        public bool[] ReadCoils(byte slaveId, ushort startAddress, ushort numberOfPoints)
        {
            return _modbusMaster.ReadCoils(slaveId, startAddress, numberOfPoints);
        }

        public bool[] ReadDiscreteInputs(byte slaveId, ushort startAddress, ushort numberOfPoints)
        {
            return _modbusMaster.ReadInputs(slaveId, startAddress, numberOfPoints);
        }

        public ushort[] ReadHoldingRegisters(byte slaveId, ushort startAddress, ushort numberOfPoints)
        {
            return _modbusMaster.ReadHoldingRegisters(slaveId, startAddress, numberOfPoints);
        }

        public ushort[] ReadInputRegisters(byte slaveId, ushort startAddress, ushort numberOfPoints)
        {
            return _modbusMaster.ReadInputRegisters(slaveId, startAddress, numberOfPoints);
        }

        public void WriteSingleCoil(byte slaveId, ushort coilAddress, bool value)
        {
            _modbusMaster.WriteSingleCoil(slaveId, coilAddress, value);
        }

        public void WriteSingleRegister(byte slaveId, ushort registerAddress, ushort value)
        {
            _modbusMaster.WriteSingleRegister(slaveId, registerAddress, value);
        }

        public void WriteMultipleCoils(byte slaveId, ushort startAddress, bool[] values)
        {
            _modbusMaster.WriteMultipleCoils(slaveId, startAddress, values);
        }

        public void WriteMultipleRegisters(byte slaveId, ushort startAddress, ushort[] values)
        {
            _modbusMaster.WriteMultipleRegisters(slaveId, startAddress, values);
        }

        public void Dispose()
        {
            if (_modbusMaster is IDisposable disposableMaster)
            {
                disposableMaster.Dispose();
            }
        }
        public void ReturnDefault()
        {

        }
    }
}
